package com.wngbms.aop._05;

import com.wngbms.aop._03.AspectAnnotationConfig;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;
import org.springframework.aop.framework.AopContext;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class AspectJProxyFactoryDemo {

    public static void main(String[] args) {
        // 被代理对象
        Map<String, String> cache = new HashMap<>();

        AspectJProxyFactory proxyFactory = new AspectJProxyFactory(cache);

//        proxyFactory.addAspect(AspectAnnotationConfig.class);
        proxyFactory.setExposeProxy(true);

        proxyFactory.addAdvice(new MethodBeforeAdvice() {
            @Override
            public void before(Method method, Object[] args, Object target) throws Throwable {
                if ("put".equals(method.getName()) && args.length ==2) {
                    Object proxy = AopContext.currentProxy();
                    System.out.printf("[BeforeAdvice] key:%s, value:%S, proxy:%s\n",
                            args[0], args[1], proxy.getClass().hashCode());
                }
            }
        });

        proxyFactory.addAdvice(new AfterReturningAdvice() {
            @Override
            public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
                if ("put".equals(method.getName()) && args.length == 2) {
                    System.out.printf("[AfterReturningAdvice] 当前存放是 Key: %s , 新存放的 Value : %s , 之前关联的 Value : %s\n ",
                            args[0],    // key
                            args[1],    // new value
                            returnValue // old value
                    );
                }
            }
        });

        Map<String, String> proxy = proxyFactory.getProxy();
        // class com.sun.proxy.$Proxy5
        System.out.println(proxy.getClass());
        System.out.println(proxy.getClass().hashCode());
        proxy.put("name", "tim");
        proxy.put("tel", "4550192");
        proxy.put("tel", "4550640");
        System.out.println(proxy.get("name"));
    }

}
